/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.serv.service.system.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yzbdl.lanius.orchestrate.serv.dto.system.RoleInsertParamDto;
import org.yzbdl.lanius.orchestrate.serv.dto.system.RoleListDto;
import org.yzbdl.lanius.orchestrate.serv.entity.system.RoleEntity;
import org.yzbdl.lanius.orchestrate.serv.entity.system.RolePermissionEntity;
import org.yzbdl.lanius.orchestrate.serv.mapper.system.RoleMapper;
import org.yzbdl.lanius.orchestrate.serv.mapper.system.RolePermissionMapper;
import org.yzbdl.lanius.orchestrate.serv.service.system.RoleService;
import org.yzbdl.lanius.orchestrate.serv.vo.system.RoleVo;
import org.yzbdl.lanius.orchestrate.common.base.entity.IdFieldEntity;
import org.yzbdl.lanius.orchestrate.common.exception.runtime.BusinessException;
import org.yzbdl.lanius.orchestrate.common.utils.MessageUtil;
import org.yzbdl.lanius.orchestrate.common.utils.SpecialCharacterUtil;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色服务
 *
 * @author chenjunhao
 * @date 2022-04-07 16:47
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements RoleService {

	@Autowired
	RolePermissionMapper rolePermissionMapper;

	/**
	 * 保存角色
	 * @param roleInsertParamDto 角色保存数据
	 * @return 更改行数
	 */
	@Override
	public int saveRole(RoleInsertParamDto roleInsertParamDto){
		LambdaQueryWrapper<RoleEntity> queryWrapper = new LambdaQueryWrapper<RoleEntity>().eq(RoleEntity::getRoleName,roleInsertParamDto.getRoleName());
		if(baseMapper.exists(queryWrapper)){
			throw new BusinessException(MessageUtil.get("system.role.same_role_name"));
		}
		RoleEntity roleEntity = RoleEntity.builder().roleName(roleInsertParamDto.getRoleName()).build();
		save(roleEntity);
		return savePermissionIdsByRoleId(roleEntity.getId(),roleInsertParamDto.getPermissionIds());
	}


	/**
	 * 修改角色
	 * @param roleEntity 角色实体
	 * @return 布尔值
	 */
	@Override
	public boolean updateRole(RoleEntity roleEntity){
		LambdaQueryWrapper<RoleEntity> queryWrapper = new LambdaQueryWrapper<RoleEntity>().eq(RoleEntity::getRoleName,roleEntity.getRoleName()).ne(IdFieldEntity::getId,roleEntity.getId());
		if(baseMapper.exists(queryWrapper)){
			throw new BusinessException(MessageUtil.get("system.role.same_role_name"));
		}
		return updateById(roleEntity);
	}

	/**
	 * 根据角色id保存权限
	 * @param roleId 角色id
	 * @param permissionIds 权限id集合
	 * @return 更改数量
	 */
	@Override
	public int savePermissionIdsByRoleId(Long roleId,List<Long> permissionIds){
		if(permissionIds==null){
			return 0;
		}
		rolePermissionMapper.delete(new LambdaQueryWrapper<RolePermissionEntity>()
				.eq(RolePermissionEntity::getRoleId,roleId)
		);
		if(!permissionIds.isEmpty()){
			List<RolePermissionEntity> rolePermissionEntityList = permissionIds.stream().map(permissionId-> RolePermissionEntity.builder()
					.permissionId(permissionId)
					.roleId(roleId)
					.build()).collect(Collectors.toList());
			return rolePermissionMapper.insertBatch(rolePermissionEntityList);
		}
		return 0;
	}

	/**
	 * 角色查询
	 * @param roleListDto 角色查询条件
	 * @param page 分页
	 * @return 角色分页列表
	 */
	@Override
	public Page<RoleVo> listRolePage(RoleListDto roleListDto , Page<RoleVo> page){
		LambdaQueryWrapper<RoleEntity> queryWrapper = new QueryWrapper<RoleEntity>().lambda()
				.like(
						StringUtils.isNotEmpty(roleListDto.getRoleName()),
						RoleEntity::getRoleName,
						SpecialCharacterUtil.escapeStr(roleListDto.getRoleName())
				);
		List<RoleVo> roles = baseMapper.queryRoleVo(
				(page.getCurrent()-1)*page.getSize(),
				page.getSize(),
				queryWrapper
		);
		page.setRecords(roles);
		page.setTotal(baseMapper.countRoleVo(ObjectUtil.clone(queryWrapper)));
		return page;
	}

	/**
	 * 删除角色
	 * @param roleId 角色id
	 * @return 更改行数
	 */
	@Override
	public int deleteRoleById(Long roleId){
		rolePermissionMapper.delete(new LambdaUpdateWrapper<RolePermissionEntity>()
			.eq(RolePermissionEntity::getRoleId,roleId)
		);
		return baseMapper.deleteById(roleId);
	}
}
